#include <stdio.h>
#include <pthread.h>
#include <sys/time.h>
#include "comm.h"
#include "hashmap.h"

unsigned long print_time(){
    struct timeval tv;
    gettimeofday(&tv, NULL);
    return tv.tv_sec * 1000000 + tv.tv_usec;
}

BUCKET *cntbuckets[SEGNUM];
pthread_t threads[SEGNUM];

int main()
{
	BYTE* pFile;
	size_t fsize;
        int i;
        unsigned long logtime;
	/**************************************
	STEP 1: read file, map file to memory;
	***************************************/
	logtime = print_time();
	pFile = open_file("./sample.log", &fsize);
	if (NULL == pFile){
		return 0;
	}

	PRINTF("read file success, size = %ld\n", fsize);
	/**************************************
	STEP 2: split file by \r\n;
	***************************************/
	t_segment *pSeg = split_file(pFile, fsize, SEGNUM);

	PRINTF("split_file return %p\n", pSeg);
	/**************************************
	STEP 3: start multithread parse segment
	***************************************/
	for (i=0; i<SEGNUM; i++){
		PRINTF("create thead args = %p\n", pSeg);
		pthread_create(threads+i, NULL, (void*)parseSeg, pSeg++);
	}

	for (i=0; i<SEGNUM; i++){
		pthread_join(threads[i], NULL);
		PRINTF("join %d\n", i);
	}

	PRINTF("stat finished!\n");
	BUCKET *maxbucket = cntbuckets[0];
	for (i=1; i<SEGNUM; i++){
		if (cntbuckets[i]->count >maxbucket->count){
			maxbucket = cntbuckets[i];
		}
	}
	printf("max count is %d, domain is %c\n", maxbucket->count, maxbucket->data[0]);
	
	logtime = print_time() - logtime;
	printf("time:%lf\n", (double)logtime/1000/1000);

	return 0;
	
}
